<template>
    <div v-bind="$attrs" class="h-[400px]" ref="container"></div>
</template>
<script setup>
    import { ref, unref, onMounted, watch } from 'vue'
    import AMapLoader from '@amap/amap-jsapi-loader';
    import setting from '/@/settings/projectSetting';
    const props = defineProps({
        poi: {
            type: Array,
            default: () => [],
        },
    })
    const emits = defineEmits(['change']);
    onMounted(() => {
        initMap();
    });
    const mapInstance = ref(null);
    const container = ref(null);
    const marker = ref(null);
    const pos = ref(null);
    const setValue = (position) => {
        emits('change', position)
    };
    const initMap = async() => {
        const AMap = await AMapLoader.load({
            key: setting.mapKey,
            version: '2.0',
            plugins: ['AMap.Geocoder'],
        })
     
        mapInstance.value = new AMap.Map(container.value, {
            zoom: 12,
            zooms: [2, 22],
        });
       
        // 添加坐标标记点
        const addMarker = (position) => {
            mapInstance.value.clearMap();
            pos.value = position;
            marker.value = new AMap.Marker({
                position,
                icon: new AMap.Icon({
                    image:
                        '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
                    size: new AMap.Size(20, 28),
                    imageSize: new AMap.Size(20, 28),
                }),
                offset: new AMap.Pixel(0, 0),
                anchor: 'bottom-center',
            });
           
            marker.value.setMap(mapInstance.value);
            setValue(position);
        };
        mapInstance.value.on('click', (e) => {
            const { lat, lng } = e.lnglat;
            emits('change', [lng, lat]);
            addMarker([lng, lat]);
        });
        return addMarker;
};
watch(() => props.poi, async (newVal) => {
    if (newVal.length > 0 && newVal[0] && newVal[1]) {
       const addMarker = await initMap();
       addMarker(newVal);
    }
});
</script>